package org.firebug.common.stock.service;

import org.firebug.common.stock.entity.StockEntity;
import org.firebug.common.stock.mapper.StockMapper;
import org.firebug.common.stock.mapper.TradeMapper;
import org.firebug.common.tools.net.HttpTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class StockService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private TradeMapper tradeMapper;
    @Resource
    private StockMapper stockMapper;

    public List<String> findAllCodes() {
        List<StockEntity> stocks = stockMapper.findAll();
        return stocks.stream().map(t -> t.getCode()).collect(Collectors.toList());
    }

    public List<StockEntity> crawl(List<String> codes) throws IOException {
        List<StockEntity> entities = new LinkedList<>();
        String url = "http://hq.sinajs.cn/list=" + StringUtils.collectionToDelimitedString(codes, ",");
        System.out.println(url);
        if(true) return null;
        String response = HttpTools.get(url);
        BufferedReader reader = new BufferedReader(new StringReader(response));
        String line;
        while ((line = reader.readLine()) != null) {
            StockEntity entity = new StockEntity();
            int s1 = line.lastIndexOf("_" + 3);
            entity.setCode(line.substring(s1, s1 + 6));
            int s2 = line.indexOf("\"" + 1);
            int e2 = line.indexOf(",");
            String name = line.substring(s2, e2);
            entity.setName(name);
            entities.add(entity);
        }
        reader.close();
        stockMapper.saveAll(entities);
        return entities;
    }
}
